﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace Html5VideoDemo.Models
{
    public class MyFileContentResult : FileResult
    {

        public long Start { get; private set; }
        public string FilePath
        {
            get;
            private set;
        }

        public MyFileContentResult(string filePath, int start, string contentType)
            : base(contentType)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentNullException("File Not Found");
            }
            this.FilePath = filePath;
            this.Start = start;
        }

        protected override void WriteFile(HttpResponseBase response)
        {
            byte[] fileData = File.ReadAllBytes(this.FilePath);
            long fileLength = fileData.LongLength;
            if (Start >= fileLength)
            {
                throw new ArgumentNullException("Start is invalid");
            }

            byte[] respData = new byte[fileLength - Start];
            System.Array.Copy(fileData, Start, respData, 0, respData.LongLength);

            /*
                Accept-Ranges:bytes                
                Content-Length:9072172
                Content-Range:bytes 0-9072171/9072172
                Content-Type:video/mp4
            */
            response.OutputStream.Write(respData, 0, respData.Length);
            response.StatusCode = 206;//HttpStatusCode.PartialContent
            response.Headers.Add("Accept-Ranges", "bytes");
            response.Headers.Add("Content-Length", respData.Length.ToString());
            response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", Start, fileLength - 1, fileLength));
        }
    }
}